package edu.zjut.hjg.saas.biz.bean;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.FactoryBean;

import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.ServerAddress;

public class MongoDBFactoryBean implements FactoryBean<DB> {

    private static final Log log = LogFactory.getLog(MongoDBFactoryBean.class);

    private DB               db;

    /**
     * @param address 服务器地址名，支持双服务器如："xxx.xxx.xx1:27017|xxx.xxx.xx2:27017"
     * @param dbName 数据库名
     */
    public MongoDBFactoryBean(String address, String dbName) {
        String[] addresses = address.split("\\|");
        List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
        for (String addr : addresses) {
            String[] sAddrs = addr.split(":");
            String host = sAddrs[0].trim();
            int port = Integer.valueOf(sAddrs[1].trim());
            try {
                serverAddresses.add(new ServerAddress(host, port));
            } catch (UnknownHostException e) {
                log.error(e.getMessage(), e);
                throw new RuntimeException(e.getMessage(), e);
            }
        }
        if (serverAddresses.isEmpty()) {
            log.error("wrong mongoDB address");
            throw new RuntimeException("wrong mongoDB address");
        }
        Mongo mongo;
        if (serverAddresses.size() == 1) {
            mongo = new Mongo(serverAddresses.get(0));
        } else {
            mongo = new Mongo(serverAddresses.get(0), serverAddresses.get(1));
        }
        this.db = mongo.getDB(dbName);
    }

    @Override
    public DB getObject() throws Exception {
        return db;
    }

    @Override
    public Class<?> getObjectType() {
        return DB.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
